import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, InputNumber, message } from 'antd';
import { createCourseChapter, updateChapter } from '@/services/courseManagementApi';

const { TextArea } = Input;

interface ChapterFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  courseId: number;
  initialValues?: COURSE.ChapterModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const ChapterForm: React.FC<ChapterFormProps> = ({
  visible,
  mode,
  courseId,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
      }
    }
  }, [visible, mode, initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      if (mode === 'create') {
        await createCourseChapter(courseId, values);
        message.success('章节创建成功');
      } else {
        await updateChapter(initialValues!.id, values);
        message.success('章节更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '章节创建失败' : '章节更新失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '添加章节' : '编辑章节'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={500}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          sort_order: 10,
        }}
      >
        <Form.Item
          name="title"
          label="章节标题"
          rules={[{ required: true, message: '请输入章节标题' }]}
        >
          <Input placeholder="请输入章节标题" />
        </Form.Item>

        <Form.Item name="description" label="章节描述">
          <TextArea rows={3} placeholder="请输入章节描述" />
        </Form.Item>

        <Form.Item
          name="sort_order"
          label="排序"
          rules={[{ required: true, message: '请输入排序值' }]}
        >
          <InputNumber
            min={1}
            placeholder="请输入排序值"
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ChapterForm;
